package com.ctshk.rpc.order.season.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.PacificUtil;
import com.ctshk.rpc.insurance.req.taiping.AcceptReq;
import com.ctshk.rpc.insurance.req.taiping.BaseInfo;
import com.ctshk.rpc.insurance.req.taiping.PlanConsult;
import com.ctshk.rpc.insurance.req.tp.*;
import com.ctshk.rpc.insurance.service.IInsuranceService;
import com.ctshk.rpc.order.season.entity.SeasonOrderInsurance;
import com.ctshk.rpc.order.season.entity.SeasonOrderTourist;
import com.ctshk.rpc.order.season.mapper.SeasonOrderInsuranceMapper;
import com.ctshk.rpc.order.season.mapper.SeasonOrderMapper;
import com.ctshk.rpc.order.season.mapper.SeasonOrderTouristMapper;
import com.ctshk.rpc.order.season.service.ISeasonOrderInsuranceService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 套票旅客保险表 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-24
 */
@DubboService
public class SeasonOrderInsuranceServiceImpl extends ServiceImpl<SeasonOrderInsuranceMapper, SeasonOrderInsurance> implements ISeasonOrderInsuranceService {

    @Autowired
    private SeasonOrderInsuranceMapper insuranceMapper;

    @Autowired
    private SeasonOrderTouristMapper touristMapper;
    @Autowired
    private SeasonOrderMapper seasonOrderMapper;

    //保险服务
    @DubboReference
    private IInsuranceService insuranceService;

    @DubboReference
    private ISysUserService iSysUserService;

    /* @MethodName: 保险下单
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/31 20:51
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void placeAnOrder(Long orderId, TokenUser tokenUser) {

        //获取当前用户信息
        UserDTO user = iSysUserService.getUser(new UserDTO().setId(tokenUser.getId()));
        try {
            List<SeasonOrderInsurance> insuranceList = getOrderInsuranceList(orderId);
//            if(CollectionUtils.isNotEmpty(insuranceList)){
//                InsuranceUnderwritingReq   underwritingReq=new InsuranceUnderwritingReq();
//                underwritingReq.setUserId(user.getId());
//                underwritingReq.setDepartmentId(user.getDeptId());
//                underwritingReq.setDepartment(user.getDept());
//                underwritingReq.setOrderNumber(String.valueOf(orderId));
//                List<AcceptReq>  list=new LinkedList<>();
//                for(SeasonOrderInsurance insurance:insuranceList){
//                    List<AcceptReq> accept=packJoinInsuranceReq(insurance);
//                    list.addAll(accept);
//                }
//                BigDecimal totalFee=insuranceList.stream().map(a->a.getInsurancePrice()).reduce(BigDecimal.ZERO,BigDecimal::add);
//                underwritingReq.setAcceptReqList(list);
//                underwritingReq.setBusinessType(SystemBusinessType.SEASON.getCode());//业务类型
//                underwritingReq.setTotalFee(totalFee);
//                InsuranceInsuredDTO insuranceInsuredDTO = insuranceService.sendProposalContent(underwritingReq);
//            }


        } catch (Exception e) {
            new BusinessException(SystemError.SEASON_TICKET_20032, e);
        }


    }


    /* @MethodName: 获取保险信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/1 9:37
     **/
    private List<SeasonOrderInsurance> getOrderInsuranceList(Long orderId) {

        return insuranceMapper.selectList(
                new QueryWrapper<SeasonOrderInsurance>().lambda()
                        .eq(SeasonOrderInsurance::getOrderId, orderId)
                        .eq(SeasonOrderInsurance::getIsDeleted, IsDeletedCode.NO.getCode())
        );
    }


    /**
     * 封装参保请求参数
     *
     * @param insurance 保单
     * @return
     */
    public List<AcceptReq> packJoinInsuranceReq(SeasonOrderInsurance insurance) {
        List<AcceptReq> list = new ArrayList<>();
        AcceptReq acceptReq = new AcceptReq();
        //基本資訊
        BaseInfo guMainDto = new BaseInfo();
        guMainDto.setAgreementNo(PacificUtil.AGREEMENTNO);
        guMainDto.setIsElectronicPolicyInd("1");
        guMainDto.setEmailReceiverType("0");
        guMainDto.setIntermediaryCode(PacificUtil.INTERMEDIARYCODE);
        guMainDto.setSolutionCode(PacificUtil.SOLUTIONCODE);
        guMainDto.setOperatorCode(PacificUtil.OPERATORCODE);
        acceptReq.setGuMainDto(guMainDto);
        //投保人
        SeasonOrderTourist applyer = touristMapper.selectById(insurance.getPolicyHolderId());
        if (applyer != null) {
            //投保人資訊
            ApplicantInfo appliGuRelatedPartyDto = new ApplicantInfo();
            appliGuRelatedPartyDto.setAge(applyer.getBirthday().until(LocalDate.now()).getYears() + "");
            appliGuRelatedPartyDto.setBirthDate(DateUtil.fmtLocalDate(applyer.getBirthday(), "yyyy-MM-dd"));
            appliGuRelatedPartyDto.setIdentifyNumber(applyer.getCertificatesNumber());
            //证件类型 + 联系地址
            //证件类型 能否对应上？00(香港身份证)  03(护照)  06(返乡证)
            appliGuRelatedPartyDto.setIdentifyType(applyer.getCertificatesType());
            //  appliGuRelatedPartyDto.setInsuredAddress("通讯地址");
            appliGuRelatedPartyDto.setSex(applyer.getGender().toString());
            appliGuRelatedPartyDto.setMobilePhone("");
            appliGuRelatedPartyDto.setInsuredName("WUYUANCHANG");
            appliGuRelatedPartyDto.setInsuredEName("Asuna");
            //acceptReq.setAppliGuRelatedPartyDto(appliGuRelatedPartyDto);
        }
        //計劃資訊列表
        List<PlanConsult> guItemAcciDetailDtoList = new ArrayList<>();
        PlanConsult guItemAcciDetailDto = new PlanConsult();
        guItemAcciDetailDto.setItemDetailNo(insurance.getInsuranceId().toString());
        guItemAcciDetailDto.setRationType(insurance.getRationType());
        guItemAcciDetailDto.setRemark("01");
        guItemAcciDetailDtoList.add(guItemAcciDetailDto);
        //被保人資訊列表
        List<InsuredInfo> guItemAcciListDtoList = new ArrayList<>();
        //旅客参保信息
        List<SeasonOrderTourist> touristList = seasonOrderMapper.getTouistList(insurance.getOrderId(), insurance.getInsuredPerson());
        if (touristList != null && touristList.size() > 0) {
            //被保人資訊列表
            for (SeasonOrderTourist tourist : touristList) {
                InsuredInfo guItemAcciListDto = new InsuredInfo();
                guItemAcciListDto.setAge(DateUtil.getAge(tourist.getBirthday()).toString());
                guItemAcciListDto.setBirthday(DateUtil.fmtLocalDate(tourist.getBirthday(), "yyyy-MM-dd"));
                guItemAcciListDto.setSex(String.valueOf(tourist.getGender()));
                guItemAcciListDto.setClientCName(tourist.getTouristName());
                //guItemAcciListDto.setClientNo(CharUtil.getChar(6));
                guItemAcciListDto.setIdentifyNoA(tourist.getCertificatesNumber());
                //证件类型
                // String identifyTypeA = PacificUtil.getIdentifyType(tourist.getCertificatesType());
                guItemAcciListDto.setIdentifyTypeA("03");
               // guItemAcciListDto.setItemDetailNo(guItemAcciDetailDto.getItemDetailNo());
              //  guItemAcciListDto.setRelationship("99");
                //年龄类型
                //    String remark3 = PacificUtil.getAgeType(tourist.getAge());
                guItemAcciListDto.setRemark3("28");
                guItemAcciListDtoList.add(guItemAcciListDto);
            }
        }
        //險別咨訊
        RiskConsult guRiskDto = new RiskConsult();
        guRiskDto.setRiskCode(insurance.getRationType());
        guRiskDto.setStartDate(DateUtil.fmtLocalDate(insurance.getInsuranceStartDate().toLocalDate(), "yyyy-MM-dd"));
        guRiskDto.setEndDate(DateUtil.fmtLocalDate(insurance.getInsuranceEndDate().toLocalDate(), "yyyy-MM-dd"));
        guRiskDto.setStartPlace("");
        guRiskDto.setEndPlace("");
        acceptReq.setGuRiskDto(guRiskDto);
        //其它信息
        OtherInfo otherInfo = new OtherInfo();
        otherInfo.setSerialNo(CharUtil.getRandomStr(5));
        acceptReq.setOtherInfo(otherInfo);
       // acceptReq.setGuItemAcciListDtoList(guItemAcciListDtoList);
        acceptReq.setGuItemAcciDetailDtoList(guItemAcciDetailDtoList);
        list.add(acceptReq);
        return list;
    }
}
